<?php

/**
* article.php
*
* Create on 2015-1-19
* Create by TT 
*/
namespace haibao\www\business;

use \haibao\www\data\Article as ArticleData;

class Article extends \haibao\www\business\Base {
	 
	/**
	 * 添加文章
	 * @param \haibao\cms\model\data\Article $articleModel        	
	 */
	public static function addArticle($articleModel) {
		self::checkOperation(self::FUNC_CODE_ARTICLE_ADD);
		self::checkData($articleModel);
		
		$articleModel->Content = self::formatHtml($articleModel->Content);
		
		$articleData = new ArticleData();
		//添加内容仓库
		$articleModel->ContentDepotId = self::addContentDepot($articleModel->Content);
		
		$articleModel = self::processArticleRelationModel($articleModel);

		$articleData->addArticle ($articleModel);
		
		//添加历史记录
		self::addArticleHistory($articleModel);
	}
	
	/**
	 * 修改文章信息
	 *
	 * @param \haibao\cms\model\data\Article $articleModel        	
	 * @throws Exception
	 */
	public static function updateArticle($articleModel){
		self::checkOperation(self::FUNC_CODE_ARTICLE_UPDATE);
		self::checkData($articleModel);
		$articleModel->Content = self::formatHtml($articleModel->Content);
		$articleData = new ArticleData();
		//修改内容仓库
		$articleData->updateContentDepot($articleModel->ContentDepotId, $articleModel->Content);
	
		$articleModel = self::processArticleRelationModel($articleModel,false);
		
		$articleData->updateArticle($articleModel);
		
		//添加历史记录
		self::addArticleHistory($articleModel,true);
		
	}
	
	/**
	 * 修改文章状态
	 *
	 * @param int $articleId        	
	 * @param int $status        	
	 */
	public static function updateArticleStatus($articleId,$status){
		self::checkOperation(self::FUNC_CODE_ARTICLE_UPDATE);
		self::checkArticleId($articleId);
		$articleData = new ArticleData();
		$articleData->updateArticleStatus($articleId, $status);	
		$arrSet['Id'] = $articleId;
		$arrSet['Status'] = $status;
		$arrSet['CreateBy'] = self::getCurrentUser ()->Id;
		$arrSet['UpdateTime'] = new \DateTime();
		self::saveOperateHistory(self::FUNC_CODE_ARTICLE_UPDATE, $arrSet);
	}
	
	/**
	 * 修改文章等级
	 * @param int $articleId
	 * @param int $level
	 */
	public static function updateArticleLevel($articleId,$level){
		self::checkOperation(self::FUNC_CODE_ARTICLE_UPDATE);
		self::checkArticleId($articleId);
		$articleData = new ArticleData();
		$articleData->updateArticleLevel($articleId, $level);
		$arrSet['Id'] = $articleId;
		$arrSet['Level'] = $level;
		$arrSet['CreateBy'] = self::getCurrentUser ()->Id;
		$arrSet['UpdateTime'] = new \DateTime();
		self::saveOperateHistory(self::FUNC_CODE_ARTICLE_UPDATE, $arrSet);
	}
	
	
	/**
	 * 修改文章审核状态
	 *
	 * @param int $articleId        	
	 * @param int $auditType        	
	 */
	public static function updateArticleAuditType($articleId,$auditType){
		self::checkOperation(self::FUNC_CODE_ARTICLE_UPDATE);
		self::checkArticleId($articleId);
		$articleData = new ArticleData();
		$articleData->updateArticleAuditType($articleId, $auditType);
		
		$arrSet['Id'] = $articleId;
		$arrSet['AuditType'] = $auditType;
		$arrSet['CreateBy'] = self::getCurrentUser ()->Id;
		$arrSet['UpdateTime'] = new \DateTime();
		self::saveOperateHistory(self::FUNC_CODE_ARTICLE_UPDATE, $arrSet);
	}
	
	/**
	 * 得到某一文章实体
	 *
	 * @param int $articleId        	
	 */
	public static function getArticleById($articleId){
		self::checkArticleId($articleId);
		$articleData = new ArticleData();
		return $articleData->getOneById($articleId);
	}
	
	/**
	 * 得到某一文章
	 *
	 * @param \haibao\cms\model\filter\Article $articleFilter
	 */
	public static function getArticleModel($articleFilter){
		$articleData = new ArticleData();
		return $articleData->getOne($articleFilter);
	}
	
	/**
	 * 查询文章
	 *
	 * @param \haibao\cms\model\filter\Article $articleFilter        	
	 */
	public static function getArticleList($articleFilter){
		$articleData = new ArticleData();
		return $articleData->getAll($articleFilter);
	}
	
	/**
	 * 统计编辑文章数列表
	 * @param array $queryArr(
	 * 					createBy,title,level,tagId,publishTimeType,startDate,endDate,page
	 * 				)
	 * @param bool $isEditorSta  是否编辑文章统计
	 */
	public static function getArticleStatisticList($queryArr,$isEditorSta = true){
		$articleData = new ArticleData();
		return $articleData->getArticleStatisticList($queryArr,$isEditorSta);
	}
	
	/**
	 * 获取第一张图
	 */
	public static function getFirstPic($articleIds){
		$articleData = new ArticleData();
		return $articleData->getFirstPic($articleIds);
	}
	/**
	 * 修改文章影响数
	 * @param int $articleId
	 * @param int $num
	 */
	public static function updateEditClickNumByArticleId($articleId,$num){
		self::checkOperation(self::FUNC_CODE_ARTICLE_UPDATE);
		$articleData = new ArticleData();
		$articleData->updateEditClickNumByArticleId($articleId, $num);
		
		$arrSet['Id'] = $articleId;
		$arrSet['EditClickNum'] = $num;
		self::saveOperateHistory(self::FUNC_CODE_ARTICLE_UPDATE, $arrSet);
	}
	
	public static function getProImageByArticleId($articleId){
		$articleData = new ArticleData();
		$data=array();
		if(empty($articleId)){
			throw new BusinessException('文章id不能为空');
		}
		$data = $articleData->getProImageByArticleId($articleId);	
		return $data;
	}

	/**
	 * 设置图片类型
	 * @param : int $articleId 文章ID
	 * @param : int $imgId 图片ID
	 * @param : int $imgType 图片类型
	 * @param : int $level 等级
	 */
	public static function setImageType($articleId,$imgId,$imgType,$level){
		if(empty($articleId)){
			throw new BusinessException('文章id不能为空');
		}
		if(empty($imgId)){
			throw new BusinessException('图片id不能为空');
		}

		$imageInfo = current(\haibao\cms\business\ImageLibrary::getImagesById($imgId));
		if($imageInfo){
			$articleData = new ArticleData();
			$articleProId = $articleData->setImageType($articleId,$imageInfo,$imgType,$level);
			
			$imageLibraryData = new \haibao\cms\data\ImageLibrary();
			$imageLibraryData->updateImageStatus($imgId,\haibao\cms\model\data\ImageLibrary::STATUS_ENABLE,self::getCurrentUser()->UserName);
			return $articleProId;
		}
		
	}
	/**
	 * 删除自定义图片类型（导读图）
	 */
	public static function delProImageByProId($imageProId){
		$articleData = new ArticleData();
		$articleData->delProImageByProId($imageProId);
	}
	
	/**
	 * 得文章导读图
	 * @param array $articleIds
	 * @param int $level
	 * @return array(ArticleId=>ImageId)
	 */
	public static function getProImageFigure($articleIds,$level){
		$articleData = new ArticleData();
		return $articleData->getProImageFigure($articleIds, $level);
	}

	/**
	 *
	 * @param int $articleId
	 * @return array
	 */
	public static function getArticleAppCloumn($articleId){
		$articleData = new ArticleData();
		return $articleData->getArticleAppCloumn($articleId);
	}
	
	/**
	 * 通过文章ID得到它的主标签ID
	 * @param array $articleIds
	 * @return array(Article=>TagId)
	 */
	public static function getArticlePrimaryTag($articleIds){
		$articleData = new ArticleData();
		return $articleData->getArticlePrimaryTag($articleIds);
	}
	
	/**
	 * 删除文章标签
	 * @param int $articleId
	 * @param int $tagId
	 * @throws BusinessException
	 */
	public static function delArticleTag($articleId,$tagId){
		self::checkOperation(self::FUNC_CODE_ARTICLE_UPDATE);
		if(empty($articleId)){
			throw new BusinessException('文章id不能为空');
		}
		if(empty($tagId)){
			throw new BusinessException('文章标签不能为空',self::DATA_ERROR_ARTICLE_TAG);
		}
		$articleData = new ArticleData();
		$articleData->delArticleTag($articleId, $tagId);
	}
	
	/**
	 * 批量添加文章标签
	 * @param array($articleModel)
	 */
	public static function batchUpdateAircleTag($articleModels,$tagIds,$articleIds){
		self::checkOperation(self::FUNC_CODE_ARTICLE_UPDATE);
	
		if($articleModels){
			$makeTagArticleIds = array();
			$articleData = new ArticleData();
			if(empty($tagIds)){
				throw new BusinessException('文章标签不能为空',self::DATA_ERROR_ARTICLE_TAG);
			}
			$articleTag = self::checkArticleTags($articleIds, $tagIds);
			foreach($articleModels as $key=>$articleModel){
	
				self::checkArticleId($articleModel->Id);
				if(empty($articleModel->ArticleTag)){
					throw new BusinessException('文章标签不能为空',self::DATA_ERROR_ARTICLE_TAG);
				}
				foreach($articleModel->ArticleTag as $k=>$articleTagModel){
					if(isset($articleTag[$articleModel->Id]) && in_array($articleTagModel->TagId, $articleTag[$articleModel->Id])){
						unset($articleModels[$key]->ArticleTag[$k]);
					}
				}
				if($articleModels[$key]->ArticleTag){
					array_push($makeTagArticleIds, $articleModel->Id);
					$articleData->batchUpdateAircleTag($articleModels[$key]);
					$articleModels[$key]->Content ="";
					self::addArticleHistory($articleModels[$key],true);
				}
			}
			return $makeTagArticleIds;
		}else{
			throw new BusinessException('文章不能为空',self::DATA_EMPTY);
		}
	}
	
	/**
	 *
	 * @param int $articleIds
	 * @return array
	 */
	public static function getPublishedArticleIds($articleIds){
		$articleData = new ArticleData();
		return $articleData->getPublishedArticleIds($articleIds);
	}
	
	/**
	 * 根据filter得到文章图片
	 * @param image 的 filter $filter object
	 */
	public static function getArticleImageByFilter($query){
		$articleData = new ArticleData();
		return $articleData->getQueryResult($query);
	}
	
	public static function getOldAticleId($articleIds,$isNewId = true){
		$articleData = new ArticleData();
		return $articleData->getOldAticleId($articleIds,$isNewId);
	}
	
	/**
	 * 根据文章id判断是否有投票，有则返回'热力投票'标签array，
	 * @param unknown $articleIds
	 * return array();
	 */
	public static function getVoteTagsById($articleIds){
		$articleVoteData = new \haibao\cms\data\ArticleVote;
		return $articleVoteData->getVoteTag($articleIds);
	}
	/**
	 * 文章发布信息存入数据库 用于计划任务同步FTP
	 * @param Int $articleId
	 * @param  Array $synchroArr 同步数据
	 */
	public static function articlePublishSynchro($articleId,$synchroArr){
	
		$data = new ArticleData();
		$data->articlePublishSynchro($articleId, $synchroArr);
	}
	/**
	 * 处理文章页面进入图库
	 */
	public static function getPicBrowse($oldArticleId){
		
		$data = new ArticleData();
		return $data->getPicBrowse($oldArticleId);
	}
	
	private static function processArticleRelationModel($articleModel,$isAdd = true){
		//处理分页
		$articleModel = self::getArticlePageContent($articleModel);
	
		//if($isAdd){
			//文章导读图
			$articleModel = self::getArticleProImageModels($articleModel);
		//}
		return $articleModel;
	}
	
	private static function addArticleHistory($articleModel,$isEdit = false){
		self::addArticleHistoryModel($articleModel->Id,$articleModel->Content);
		$operateType = self::FUNC_CODE_ARTICLE_ADD;
		if($isEdit){
			$operateType = self::FUNC_CODE_ARTICLE_UPDATE;
		}
		self::saveOperateHistory($operateType, $articleModel->toArray(true,true));
	}
	
	private static function getArticlePageContent($articleModel){
		$pageContentArr = self::chooseContentPage($articleModel->Content,$articleModel->SaveActive);
		
		
		if(!empty($pageContentArr['pageContents'])){
			$articleContentModels = array();
			foreach($pageContentArr['pageContents'] as $key=>$content){
				$articleContentModel = new \haibao\cms\model\data\ArticleContent();
				$articleContentModel->Content = $content;
				$articleContentModel->CurrentPage = $key + 1;
				$articleContentModels[] = $articleContentModel;
			}
			$articleModel->ArticleContent = $articleContentModels;
		}
	
		$imageIdArr = array();
		if(!empty($pageContentArr['allImageIds']) && !empty($pageContentArr['imageIds'])){
			$imageIdArr = $pageContentArr['allImageIds'];
			$articleModel->ArticleImage = self::getArticleImageModels($imageIdArr, $pageContentArr['imageIds']);
		}
	
		if(!empty($pageContentArr['productIds'])){
			$articleProductModels = array();
			foreach($pageContentArr['productIds'] as $key=>$productIds){
				if($productIds){
					foreach ($productIds as $id){
						$articleProductModel = new \haibao\cms\model\data\ArticleProduct();
						$articleProductModel->ProductId = $id;
						$articleProductModel->CurrentPage = $key + 1;
						$articleProductModels[] = $articleProductModel;
					}
				}
			}
			$articleModel->ArticleProduct = $articleProductModels;
		}
	
		$articleModel->PicCount = count($imageIdArr);
	
		//更新图片状态
		if($imageIdArr){
			$imageLibraryBusiness = new \haibao\cms\business\ImageLibrary();
			$imageLibraryModels = $imageLibraryBusiness->updateImageStatus($imageIdArr);
		}
	
		return $articleModel;
	}
	
	private static function getArticleImageModels($imageIdArr,$pageImageIds){
		$articleImageModels = array();
		$imageLibraryBusiness = new \haibao\cms\business\ImageLibrary();
		$imageLibraryModels = $imageLibraryBusiness->getImagesById($imageIdArr);
		if($imageLibraryModels){
			if(!empty($pageImageIds)){
				foreach($pageImageIds as $key=>$imageIds){
					if($imageIds){
						foreach ($imageIds as $k=>$id){
							foreach($imageLibraryModels as $imageLibraryModel){
								if($imageLibraryModel->Id == $id){
									$articleImageModel = new \haibao\cms\model\data\ArticleImage();
									$articleImageModel->ImageId = $id;
									$articleImageModel->Height = $imageLibraryModel->Height;
									$articleImageModel->Width = $imageLibraryModel->Width;
									$articleImageModel->PicUrl = $imageLibraryModel->Filename;
									$articleImageModel->Description = $imageLibraryModel->Description;
									$articleImageModel->CurrentPage = $key + 1;
									$articleImageModel->PicOrder = $k + 1;
									$articleImageModels[] = $articleImageModel;
									break;
								}
							}
						}
					}
				}
			}
		}
		return $articleImageModels;
	}
	
	private static function getArticleProImageModels($articleModel){
		$articleProImageModels = array();
		if($articleModel->ArticleImage){
			foreach($articleModel->ArticleImage as $articleImageModel){
				$articleProImageIntroModel = new \haibao\cms\model\data\ArticleProImage();
				$articleProImageIntroModel->ImageId = $articleImageModel->ImageId;
				$articleProImageIntroModel->Height = $articleImageModel->Height;
				$articleProImageIntroModel->Width = $articleImageModel->Width;
				$articleProImageIntroModel->PicUrl = $articleImageModel->PicUrl;
				$articleProImageIntroModel->PicType = $articleProImageIntroModel::PIC_TYPE_INTRO;
				$articleProImageIntroModel->Level = $articleProImageIntroModel::Level_ZERO;
				$articleProImageModels[] = $articleProImageIntroModel;
				$articleProImageModel = new \haibao\cms\model\data\ArticleProImage();
				$articleProImageModel->ImageId = $articleImageModel->ImageId;
				$articleProImageModel->Height = $articleImageModel->Height;
				$articleProImageModel->Width = $articleImageModel->Width;
				$articleProImageModel->PicUrl = $articleImageModel->PicUrl;
				$articleProImageModel->PicType = $articleProImageModel::PIC_TYPE_COVER;
				$articleProImageModel->Level = $articleProImageModel::Level_ZERO;
				$articleProImageModels[] = $articleProImageModel;
				break;
			}
			$articleModel->ArticleProImage = $articleProImageModels;
		}
		
		return $articleModel;
	}
	
	private static function checkArticleId($articleId){
		if(empty($articleId)){
			throw new BusinessException('文章ID不能为空',self::DATA_ERROR_ARTICLE_ID);
		}
	}
	
	private static function checkData($articleModel){
		if(empty($articleModel->Title)){
			throw new BusinessException('文章标题不能为空',self::DATA_ERROR_ARTICLE_TITLE);
		}
		if(!$articleModel->Content && $articleModel->SaveActive) {
			throw new BusinessException('文章内容不能为空',self::DATA_ERROR_ARTICLE_CONTENT);
		}
		if(empty($articleModel->Source) && !empty($articleModel->SaveActive) ){
			throw new BusinessException('文章来源不能为空',self::DATA_ERROR_ARTICLE_SOURCE);
		}
		if(empty($articleModel->ArticleTag) && !empty($articleModel->SaveActive) ){
			throw new BusinessException('文章标签不能为空',self::DATA_ERROR_ARTICLE_TAG);
		}
		if(!empty($articleModel->ArticleTag)){
			$hasPrimaiyTag = false;
			foreach($articleModel->ArticleTag as $articleTagModel){
				if($articleTagModel->IsPrimaiy){
					$hasPrimaiyTag = true;
					break;
				}
			}
			if(!$hasPrimaiyTag && !empty($articleModel->SaveActive)){
				throw new BusinessException('文章主标签不能为空',self::DATA_ERROR_ARTICLE_PRIMAIY_TAG);
			}
		}
	}
	
	/**
	 * 格式化内容
	 */
	private static function formatHtml($content){
		
		$content = str_replace("\r\n", '', $content); //清除换行符
		$content = str_replace("\n", '', $content); //清除换行符
		$content = str_replace("\t", '', $content); //清除制表符
		
		$content = str_replace("’", '&#39;', $content); //替换右单引号
		$content = str_replace("‘", '&#39;', $content); //替换左单引号
		
		//先置换各种无用的占行代码
		$content = str_replace('<p style=\"text-align:center;\"><br /></p>', '<p><br /></p>', $content);
		$content = str_replace('<p style=\"text-align:left;\"><br /></p>', '<p><br /></p>', $content);
		$content = str_replace('<p style=\"text-align:right;\"><br /></p>', '<p><br /></p>', $content);
		
		if (get_magic_quotes_gpc()) {
			$content = stripslashes($content);
		}else{
			
		}
		//纠错
		$articleData = new ArticleData();
		$replaceArr = $articleData->errorContentReplace ();
		if($replaceArr){
			$wrongArr = array();
			if(!empty($replaceArr['wrong'])){
				$wrongArr = $replaceArr['wrong'];
			}
			$correctArr = array();
			if(!empty($replaceArr['correct'])){
				$correctArr = $replaceArr['correct'];
			}
			$content = str_replace($wrongArr, $correctArr, $content);
		}
		return $content;
	}
	
	
	/**
	 * 内容分页、每页匹配到的图片ID与单品ID
	 */
	private static function chooseContentPage($content,$saveActive){
		$contentPageArr = array();
		$imageIdArr = array();
		$allImageIds = array();
		$productIdArr = array();
		$regStr = "/_ueditor_page_break_tag_/";
		$contentArr = preg_split($regStr, $content);
		foreach($contentArr as $k=>$v) {
			$contentPageArr[] = $v;
			$imageIds = self::getImageIds($v);
			if($imageIds){
				$allImageIds = array_merge_recursive($allImageIds,$imageIds);
			}
			$imageIdArr[] = $imageIds;
			$productIdArr[] = self::getProductIds($v);
		}
		$contentPageArr = array_filter($contentPageArr);
		if(empty($contentPageArr) && !empty($saveActive)){
			throw new BusinessException('文章内容不能为空',self::DATA_ERROR_ARTICLE_CONTENT);
		}
		
		if(empty($allImageIds) && !empty($saveActive)){
			throw new BusinessException('文章内容中不能没有图片',self::DATA_ERROR_ARTICLE_IMAGE);
		}
		
		return array('pageContents'=>$contentPageArr,'imageIds'=>$imageIdArr,'productIds'=>$productIdArr,'allImageIds'=>$allImageIds);
	}
	
	/**
	 * 分页中的图片
	 */
	private static function getImageIds($content){
		$newIds = array();
		$content = stripcslashes($content);
		// DOTO : 处理匹配老数据src
		if(preg_match_all('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$content,$imgMatch)){
			$oldImgIdArr = array();
			$imageIdArr = array();
			$pattern = '/<img[^>]*\s?rel=\"([0-9]+)\"/is';
			foreach($imgMatch[0] as $key=>$match){
				if(preg_match($pattern,$match,$rel)){
					if(strpos($match, "static.") ===false){
						array_push($oldImgIdArr,$rel[1]);
					}else{
						array_push($imageIdArr,$rel[1]);
					}	
				}
			}
			if($oldImgIdArr){
				$articleData = new ArticleData();
				$newImgIdArr = $articleData->getNewImgId($oldImgIdArr);
				$newIds = array_merge($imageIdArr, $newImgIdArr);
			} else {
				$newIds = $imageIdArr;
			}
		}
		
		return $newIds;
	}
	
	/**
	 * 分页中的单品
	 */
	private static function getProductIds($content){
		$productIdArr = array();
		$pattern = '/<a[^>]*\s?com\/product\/([0-9]+)\//is';
		$content = stripcslashes($content);
		
		if(preg_match_all($pattern, $content, $matches)){
			foreach($matches[1] as $key=>$match){
				$productIdArr[] = (int)$match;
			}
		}		
		return $productIdArr;
	}	
	
	private static function addContentDepot($content){
		$articleData = new ArticleData();
		$contentModel = new \haibao\cms\model\data\ContentDepot();
		$contentModel->Content = $content;
		$contentModel->CreateBy = self::getCurrentUser ()->Id;
		$contentModel->CreateTime = new \DateTime();
		$articleData->add($contentModel);
		return $contentModel->Id;
	}
	
	private static function addArticleHistoryModel($articleId,$content){
		$articleData = new ArticleData();
		$historyModel = new \haibao\cms\model\data\ArticleHistory();
		$historyModel->Content = $content;
		$historyModel->CreateBy = self::getCurrentUser ()->Id;
		$historyModel->CreateTime = new \DateTime();
		$historyModel->ArticleId = $articleId;
		$articleData->add($historyModel);
	}
	
	/**
	 * 标签在文章中是否存在
	 */
	private static function checkArticleTags($articleId,$tagIds){
		$articleData = new ArticleData();
		return $articleData->checkArticleTags($articleId,$tagIds);
	}
	/**
	 * 通过文章id获得点击数
	 */
	public static function getClickNumsByArticleIds($articleIds){
		$articleData = new ArticleData();
		return $articleData->getClickNumsByArticleIds($articleIds);
	}
	/**
	 * 通过文章ID获得绑定图集Id
	 */
	public static function getImageCollIdsByArticleIds($articleIds){
		if(empty($articleIds)){
			throw new BusinessException('文章id不能为空');
		}
		
		$articleData = new ArticleData();
		return $articleData->getImageCollIdsByArticleIds($articleIds);
	}
	/**
	 * 图集关联文章
	 */
	public static function addImageCollectiveArticle($model,$articleId){
		self::checkOperation(self::FUNC_CODE_IMAGECOLLECTIVEARTICLE_ADD);
		
		if($model && !$model->ArticleId){
			throw new BusinessException('文章id不能为空',self::DATA_EMPTY_ID);
		}
// 		if(!$model->ImageCollectiveId){
// 			throw new BusinessException('图集id不能为空',self::DATA_EMPTY_ID);
// 		}
		$articleData = new ArticleData();
		
		$articleData->addImageCollectiveArticle($model,$articleId);
		if($model){
			self::saveOperateHistory(self::FUNC_CODE_IMAGECOLLECTIVEARTICLE_ADD, $model->toArray());
		}
	}
}